<!doctype html>
<html lang="ah-cn">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Todo List</title>
	<link rel="stylesheet" href="/css/base.css">
	<link rel="stylesheet" href="/css/index.css">
	<link rel="stylesheet" href="/css/nprogress.css">
	<style>
		.choose-input {
			position: absolute;
			top: 10px;
			left: 0;
			width: 30px;
			height: 30px;
		}
	</style>
</head>

<body>
	<section class="todoapp">
		<header class="header">
			<h1>todos</h1>
			<input type="text" class="new-todo" placeholder="What needs to be done?" autofocus id="task">
		</header>
		<!-- This section should be hidden by default and shown when there are todos -->
		<section class="main">
			<input class="toggle-all" type="checkbox">
			<ul class="todo-list" id="todo-list">
				<!-- These are here just to show the structure of the list items -->
				<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
			</ul>
		</section>
		<!-- This footer should hidden by default and shown when there are todos -->
		<footer class="footer">
			<!-- This should be `0 items left` by default -->
			<span class="todo-count"><strong id="count">0</strong> item left</span>
			<!-- Remove this if you don't implement routing -->
			<ul class="filters">
				<li>
					<a class="selected" href="javascript:;" id="all">All</a>
				</li>
				<li>
					<a href="javascript:;" id="active">Active</a>
				</li>
				<li>
					<a href="javascript:;" id="completed">Completed</a>
				</li>
			</ul>
			<!-- Hidden if no completed items are left ↓ -->
			<button class="clear-completed" id="clear">Clear completed</button>
		</footer>
	</section>
	<script src="/js/jquery-3.5.1.min.js"></script>
	<script src="/js/template-web.js"></script>
	<script src="/js/nprogress.js"></script>
	<!-- 任务列表模板 -->
	<script type="text/html" id="tpl">
		{{each data}}
		<li class="{{$value.completed ? 'completed' : ''}}">
			<div class="view">
				<input class="choose-input" type="checkbox" {{$value.completed ? 'checked' : ''}}>
				<label>{{$value.title}}</label>
				<button class="destroy" data-id="{{$value._id}}"></button>
			</div>
			<input class="edit" value="{{$value.title}}">
		</li>
		{{/each}}
	</script>

	<script type="text/javascript">
		// 存放todo list的数组
		let todos = [];
		// 当前显示的链接
		let currentLink = 'all';

		// 渲染todo list
		render();
		// 获取未完成的todo数目
		getNoCompletedTodoCount();

		// 当页面中有ajax请求发送时触发
		$(document).on('ajaxStart', function () {
			NProgress.start();
		});

		// 当页面中有ajax请求完成时触发
		$(document).on('ajaxComplete', function () {
			NProgress.done();
		});

		// todo输入框回车事件
		$('#task').on('keyup', function (e) {
			let keyCode = e.keyCode;
			// 若用户按下了回车键
			if (keyCode == 13) {
				// 若用户输入了内容，发送添加todo请求，否则阻止代码向下执行
				let todoValue = $(this).val().trim();
				if (todoValue.length == 0) return alert('请输入todo');
				$.ajax({
					type: 'post',
					url: '/todo/addTask',
					data: {
						title: todoValue
					},
					success: function (res) {
						// todo添加成功
						// 清空todo输入框
						$('#task').val('');
						// 重新渲染todo list
						render();
						// 获取未完成的todo数目
						getNoCompletedTodoCount();
					},
					error: function (err) {
						// todo添加失败
						let info = JSON.parse(err.responseText);
						return alert(info.message);
					}
				});
			}
		});

		// todo list删除按钮被点击事件
		$('#todo-list').on('click', '.destroy', function () {
			let id = $(this).attr('data-id');
			// 向服务器发送删除todo请求
			$.ajax({
				type: 'get',
				url: '/todo/deleteTask',
				data: {
					_id: id
				},
				success: (res) => {
					// 重新渲染todo list
					render();
					// 获取未完成的todo数目
					getNoCompletedTodoCount();
				}
			});
		});

		// todos list选中状态改变事件
		$('#todo-list').on('change', '.choose-input', function () {
			// 修改状态的todo修改后的选中状态
			let state = $(this).prop('checked');
			// 向服务器发送修改请求
			$.ajax({
				type: 'post',
				url: '/todo/modifyTask',
				data: {
					_id: $(this).siblings('.destroy').attr('data-id'),
					title: $(this).siblings('label').text(),
					completed: state
				},
				success: (res) => {
					// 重新渲染todo list
					render(); // 获取未完成的todo数目
					getNoCompletedTodoCount();
				}
			});
		});

		// 显示正在进行的任务连接被点击
		$('#active').on('click', function () {
			// 过滤出未完成的todolist
			let activeArray = todos.filter(item => item.completed == false);
			// 渲染todo list
			let html = template('tpl', {
				data: activeArray
			});
			$('#todo-list').html(html);
			// 改变当前链接为active
			currentLink = 'active';
			// 更改显示正在进行中的todo链接为选中状态，其它链接为未选中状态
			$(this).addClass('selected').parent().siblings().children('a').removeClass('selected');
		});

		// 显示已完成的任务连接被点击
		$('#completed').on('click', function () {
			// 过滤出未完成的todolist
			let activeArray = todos.filter(item => item.completed == true);
			// 渲染todo list
			let html = template('tpl', {
				data: activeArray
			});
			$('#todo-list').html(html);
			// 改变当前链接为completed
			currentLink = 'completed';
			// 更改显示已完成的todo链接为选中状态，其它链接为未选中状态
			$(this).addClass('selected').parent().siblings().children('a').removeClass('selected');
		});

		// 显示全部的任务连接被点击
		$('#all').on('click', function () {
			currentLink = 'all';
			// 更改显示全部的todo链接为选中状态，其它链接为未选中状态
			$(this).addClass('selected').parent().siblings().children('a').removeClass('selected');
			// 渲染数据
			render();
		});

		// 清空已完成的todo按钮被点击
		$('#clear').on('click', function () {
			$.ajax({
				type: 'get',
				url: '/todo/clearTask',
				success: res => {
					// 冲洗渲染todo list
					render();
				}
			});
		});

		// 获取未完成的todo数目函数
		function getNoCompletedTodoCount() {
			$.ajax({
				type: 'get',
				url: '/todo/unCompletedTaskCount',
				success: (res) => {
					$('#count').text(res.num);
				}
			});
		}

		// 渲染todo list函数
		function render() {
			// 查询todo列表
			$.ajax({
				type: 'get',
				url: '/todo/task',
				success: function (res) {
					todos = res;
					let html = template('tpl', {
						data: todos
					});
					$('#todo-list').html(html);
					// 若当前链接是active，触发显示未完成todo list 链接的的点击事件
					// 若当前链接是completed，触发显示已完成todo list 链接的点击事件
					if (currentLink == 'completed') {
						$('#completed').click();
					} else if (currentLink == 'active') {
						$('#active').click();
					}
				}
			});
		}
	</script>
</body>

</html>